package com.banciyuan.bcywebview.utils.baidussp;

import android.content.Context;
import android.os.AsyncTask;
import android.text.TextUtils;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.banciyuan.bcywebview.utils.common.UIUtils;
import com.banciyuan.bcywebview.utils.http.StringRequestParam;
import com.banciyuan.bcywebview.utils.http.VolleyQueue;
import com.google.gson.Gson;

import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.message.BasicNameValuePair;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;

/**
 * Created by squall1989 on 2017/2/21.
 */

public class SspHelper {

    private HashSet<Integer> delete = new HashSet();
    private Context mContext;
    private RequestQueue mQueue;
    private long max_time = 600;
    private Gson gson;
    private int height;
    private int width;

    public static final String HOST = "http://c.ssp.baidu.com";
    public static final String KEY_PROFIX = "_sspsdk_%s.txt";

    public SspHelper(Context mContext) {
        this.mContext = mContext;
        this.mQueue = VolleyQueue.getRquestNotUseHttpDns(mContext, false);
        this.gson = new Gson();
    }

    public SspHelper(Context mContext, int width, int height) {
        this.mContext = mContext;
        this.mQueue = VolleyQueue.getRquestNotUseHttpDns(mContext, false);
        this.gson = new Gson();
        this.width = width;
        this.height = height;
    }

    private void getStrategyCache(final String adPosition, final onPerStepComplate onPerStepComplate) {
        new AsyncTask<Void, String, Strategy>() {
            @Override
            protected Strategy doInBackground(Void... params) {
                try {
                    String cache = SSPCache.read(mContext, String.format(KEY_PROFIX, adPosition));
                    if (!TextUtils.isEmpty(cache)) {
                        return gson.fromJson(cache, Strategy.class);
                    } else {
                        return null;
                    }
                } catch (Exception e) {
                    return null;
                }
            }

            @Override
            protected void onPostExecute(Strategy strategy) {
                if (strategy != null) {
                    if (strategy.getTime() + max_time * 1000 < System.currentTimeMillis()) {
                        getStategyWeb(adPosition, onPerStepComplate);
                    } else {
                        onPerStepComplate.complate(strategy);
                    }
                } else {
                    getStategyWeb(adPosition, onPerStepComplate);
                }
            }
        }.execute();
    }

    private void writeStategyCache(final String adPosition, final String json) {
        new AsyncTask<Void, Void, Boolean>() {
            @Override
            protected Boolean doInBackground(Void... params) {
                return SSPCache.write(mContext, String.format(KEY_PROFIX, adPosition), json);
            }
        }.execute();
    }

    private void getStategyWeb(final String adPosition, final onPerStepComplate onPerStepComplate) {
        List params = SspUtils.parseParams(mContext, adPosition);
        String paramsurl = URLEncodedUtils.format(params, "utf-8");
        String url = HOST + "/ecom.do" + "?" + paramsurl;

        Response.Listener<String> onSucc = new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                try {
                    Strategy strategy = gson.fromJson(response, Strategy.class);
                    strategy.setTime(System.currentTimeMillis());
                    onPerStepComplate.complate(strategy);
                    writeStategyCache(adPosition, gson.toJson(strategy));
                } catch (Exception e) {
                    onPerStepComplate.error();
                }

            }
        };

        Response.ErrorListener onError = new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                error.printStackTrace();
            }
        };
        StringRequestParam stringRequestParam = new StringRequestParam(Request.Method.GET, url, null, onSucc, onError);
        mQueue.add(stringRequestParam);
    }

    private SSPEntity getSingleStrategy(List<SSPEntity> slist) {
        List<SSPEntity> templist = new ArrayList<>();
        for (int i = 0; i < slist.size(); i++) {
            SSPEntity sspEntity = slist.get(i);
            if (!delete.contains(sspEntity.getAlliance())) {
                templist.add(sspEntity);
            }
        }
        SSPEntity result = null;
        if (templist.size() > 0) {
            result = templist.get(0);
        }
        return result;
    }

    public void getAD(final String adPosition, final onAdverListener onAdverListener) {
        getStrategyCache(adPosition, new onPerStepComplate() {
            @Override
            public void complate(Strategy strategy) {
                if (strategy != null) {
                    List params = SspUtils.parseParams(mContext, adPosition);
                    SSPEntity sspEntity = getSingleStrategy(strategy.getResult());
                    if (sspEntity != null) {
                        params.add(new BasicNameValuePair("strategyId", "" + sspEntity.getStrategyId()));
                        params.add(new BasicNameValuePair("w", String.valueOf(UIUtils.px2dip(width, mContext))));
                        params.add(new BasicNameValuePair("h", String.valueOf(UIUtils.px2dip(height, mContext))));
                        params.add(new BasicNameValuePair("isNative", "0"));
                        String paramsurl = URLEncodedUtils.format(params, "utf-8");
                        String url = HOST + "/material.do" + "?" + paramsurl;
                        Response.Listener<String> onSucc = new Response.Listener<String>() {
                            @Override
                            public void onResponse(String response) {
                                onAdverListener.onSucc(response);
                            }
                        };

                        Response.ErrorListener onError = new Response.ErrorListener() {
                            @Override
                            public void onErrorResponse(VolleyError error) {
                                onAdverListener.onfail(error.getMessage());
                            }
                        };
                        StringRequestParam stringRequestParam = new StringRequestParam(Request.Method.GET, url, null, onSucc, onError);
                        mQueue.add(stringRequestParam);
                    }

                }
            }

            @Override
            public void error() {
                onAdverListener.onfail("fail");
            }
        });
    }

    public void getClickCount(final String adPosition, final onAdverListener onAdverListener) {
        getStrategyCache(adPosition, new onPerStepComplate() {
            @Override
            public void complate(Strategy strategy) {
                List params = SspUtils.parseParams(mContext, adPosition);
                SSPEntity sspEntity = getSingleStrategy(strategy.getResult());
                params.add(new BasicNameValuePair("sid", strategy.getSid()));
                params.add(new BasicNameValuePair("alliance", "" + sspEntity.getAlliance()));
                params.add(new BasicNameValuePair("strategyId", "" + sspEntity.getStrategyId()));
                String paramsurl = URLEncodedUtils.format(params, "utf-8");
                String url = HOST + "/click.do" + "?" + paramsurl;
                Response.Listener<String> onSucc = new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        onAdverListener.onSucc(response);
                    }
                };

                Response.ErrorListener onError = new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        onAdverListener.onfail(error.getMessage());
                    }
                };
                StringRequestParam stringRequestParam = new StringRequestParam(Request.Method.GET, url, null, onSucc, onError);
                mQueue.add(stringRequestParam);
            }

            @Override
            public void error() {
                onAdverListener.onfail("fail");
            }
        });
    }

    public void getViewCount(final String adPosition, final onAdverListener onAdverListener) {

        getStrategyCache(adPosition, new onPerStepComplate() {
            @Override
            public void complate(Strategy strategy) {
                List params = SspUtils.parseParams(mContext, adPosition);
                params.add(new BasicNameValuePair("sid", strategy.getSid()));
                params.add(new BasicNameValuePair("st", "" + System.currentTimeMillis()));
                params.add(new BasicNameValuePair("queue", "0"));
                params.add(new BasicNameValuePair("hasAd", "0"));
                String paramsurl = URLEncodedUtils.format(params, "utf-8");
                String url = HOST + "/view.do" + "?" + paramsurl;
                Response.Listener<String> onSucc = new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        onAdverListener.onSucc(response);
                    }
                };

                Response.ErrorListener onError = new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        onAdverListener.onfail(error.getMessage());
                    }
                };
                StringRequestParam stringRequestParam = new StringRequestParam(Request.Method.GET, url, null, onSucc, onError);
                mQueue.add(stringRequestParam);
            }

            @Override
            public void error() {
                onAdverListener.onfail("fail");
            }
        });
    }

    public void getViewCountImpress(final String adPosition, final onAdverListener onAdverListener, final int delay) {

        getStrategyCache(adPosition, new onPerStepComplate() {
            @Override
            public void complate(Strategy strategy) {
                SSPEntity sspEntity = getSingleStrategy(strategy.getResult());
                List params = SspUtils.parseParams(mContext, adPosition);
                params.add(new BasicNameValuePair("sid", strategy.getSid()));
                params.add(new BasicNameValuePair("st", "" + System.currentTimeMillis()));
                params.add(new BasicNameValuePair("queue", String.valueOf(sspEntity.getAlliance())));
                params.add(new BasicNameValuePair("hasAd", "1"));
                params.add(new BasicNameValuePair("delay", String.valueOf(delay)));
                params.add(new BasicNameValuePair("strategyId", "" + sspEntity.getStrategyId()));
                String paramsurl = URLEncodedUtils.format(params, "utf-8");
                String url = HOST + "/view.do" + "?" + paramsurl;
                Response.Listener<String> onSucc = new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        onAdverListener.onSucc(response);
                    }
                };

                Response.ErrorListener onError = new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        onAdverListener.onfail(error.getMessage());
                    }
                };
                StringRequestParam stringRequestParam = new StringRequestParam(Request.Method.GET, url, null, onSucc, onError);
                mQueue.add(stringRequestParam);
            }

            @Override
            public void error() {
                onAdverListener.onfail("fail");
            }
        });
    }


    public interface onAdverListener {
        void onSucc(String responce);

        void onfail(String error);
    }

    private interface onPerStepComplate {
        void complate(Strategy strategy);

        void error();
    }
}
